<template>
	<!-- 定期排查填写流程页面 -->
	<view class="workApply-container" :style="{ height: `${windowHeight}px` }">
		<!-- 基础表单校验 -->
		<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" border>
			<uni-forms-item label="任务编号：" name="taskNumber">
				<uni-easyinput v-model="valiFormData.taskNumber" disabled placeholder="请输入" :inputBorder="false" />
			</uni-forms-item>
			<uni-forms-item label="所属检查计划：" required name="planId">
				<custom-tree-select :listData="checkPlanOption" disabled @selectChange="handleChange" :search="true"
					dataLabel="planCategory" dataValue="id" v-model="valiFormData.planId" />
			</uni-forms-item>
			<uni-forms-item label="检查任务名称：" required name="taskName">
				<uni-easyinput v-model="valiFormData.taskName" disabled placeholder="请输入" :inputBorder="false" />
			</uni-forms-item>
			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="检查层级：" required name="taskLevel">
				<template v-if="valiFormData.taskLevel == 1">公司级</template>
				<template v-else-if="valiFormData.taskLevel == 2">部门级</template>
				<template v-else-if="valiFormData.taskLevel == 3">班组级</template>
			</uni-forms-item>
			<uni-forms-item label="检查时间：" required name="taskTime">
				<uni-datetime-picker type="date" :clear-icon="false" disabled v-model="valiFormData.taskTime" />
			</uni-forms-item>
			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="检查执行人：" required name="examineExecutorId">
				<!-- <text> {{valiFormData.examineExecutorName}}</text> -->
				<uni-data-select :localdata="executorList" disabled v-model="valiFormData.examineExecutorId" />
			</uni-forms-item>
			<!-- 多选 -->
			<uni-forms-item label="检查参与人：" required name="examineParticipantIds	">
				<custom-tree-select :listData="allUsers" dataLabel="nickName" disabled dataValue="userId" :search="true"
					@selectChange="deptChange" :mutiple="true" v-model="valiFormData.examineParticipantIds" />

				</custom-tree-select>
			</uni-forms-item>
			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="被检查单位：" required name="passReviewUnitId">

				<custom-tree-select :listData="treeData" dataLabel="label" disabled dataValue="id" :search="true"
					:mutiple="false" v-model="valiFormData.passReviewUnitId" />

				</custom-tree-select>

			</uni-forms-item>

			<uni-forms-item label="外部人员：" required name="outPerson">
				<uni-easyinput v-model="valiFormData.outPerson" disabled placeholder="请输入" :inputBorder="false" />
			</uni-forms-item>
		</uni-forms>
		<uni-segmented-control :current="current" :values="items" style-type="text" @clickItem="changeTable" />
		<!-- <view class="hidden-num">数量</view> -->
		<template v-if="current == 0">

			<!-- <ViewTable :tableHead="tableHead" :tableList="MockTableList"/> -->
			<view class="table-container">
				<uni-table ref="table-one" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
					@selection-change="selectionChange" class="view-table">
					<uni-tr>
						<uni-th align="center" width="80">序号</uni-th>
						<!-- <uni-th align="center">检查分类</uni-th>
									<uni-th align="center">检查范围</uni-th> -->
						<uni-th align="center" width="180">检查内容</uni-th>
						<uni-th align="center" width="160">检查情况</uni-th>
						<uni-th align="center" class="fixed" width="90">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in tableData" :key="index">
						<uni-td>{{ index +1 }}</uni-td>

						<uni-td align="left">{{ item.inspectionStandard }}</uni-td>
						<uni-td align="center">
							<!-- 			{{item.isHiddenDanger}}
										<template v-if="item.isHiddenDanger">
				
											<uni-data-select v-model="item.isHiddenDanger" :localdata="hiddenData"></uni-data-select>
										</template>
										<template v-else-if="!item.isHiddenDanger">
											<uni-data-select v-model="item.isHiddenDanger" :localdata="hiddenData"></uni-data-select>
										</template> -->
							<uni-data-select v-model="item.isHiddenDanger" :localdata="hiddenData" :clear="false"></uni-data-select>

						</uni-td>
						<uni-td align="center" class="fixed">
							<view class="uni-group">
								<button class="uni-button" size="mini" type="primary" :disabled="!item.isHiddenDanger"
									@click="handleResigration(item)">登记</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>

			</view>

		</template>

		<template v-else-if="current == 1">
			<view class="table-container">
				<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
					@selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" width="80">序号</uni-th>
						<uni-th align="center" width="160">隐患名称</uni-th>
						<uni-th align="center" width="180">隐患描述</uni-th>
						<uni-th align="center" width="140">登记人</uni-th>
						<uni-th align="center" width="160">登记时间</uni-th>
						<uni-th align="center" width="180">是否现场解决</uni-th>
						<uni-th align="center" class="fixed" width="90">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in hiddentroubleInspectionRegisters" :key="item.id">
						<uni-td>{{ index +1 }}</uni-td>
						<uni-td>
							<view class="name">{{ item.hiddenDangerName }}</view>
						</uni-td>
						<uni-td align="center">{{ item.hiddenDangerDescription }}</uni-td>
						<uni-td align="center">{{ item.hazardRegistrantName }}</uni-td>
						<uni-td align="center">{{ item.rectificationTime }}</uni-td>

						<uni-td align="center">
							<template v-if="item.isSiteSolution == 1">
								<text>是</text>
							</template>

							<template v-else-if="item.isSiteSolution == 2">
								<text>否</text>
							</template>
						</uni-td>
						<uni-td class="fixed" align="center">
							<view class="uni-group">
								<!-- <button>查看</button> -->
								<button class="uni-button" size="mini" type="warn"
									@click="handleDelete(item)">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>

			</view>

		</template>


		<button type="primary" @click="submit('valiForm')" class="submit-btn">
			确认
		</button>
		<!-- //登记抽屉 @change="change($event,'showLeft')" -->
		<uni-drawer ref="showLeft" mode="left" width="390">
			<view class="close">
				<uni-forms ref="hiddenForm" :rules="rules" :modelValue="hiddenForm" border>
					<uni-forms-item label="隐患名称：" name="hiddenDangerName">
						<uni-easyinput v-model="hiddenForm.hiddenDangerName" disabled placeholder="请输入"
							:inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="隐患等级：" required name="hiddenDangerLevel">
						<uni-data-select :localdata="hiddenLevelOption" v-model="hiddenForm.hiddenDangerLevel" />
					</uni-forms-item>
					<uni-forms-item label="隐患现场图片：" required name="taskName">
						<uni-easyinput v-model="valiFormData.taskName" placeholder="请输入" :inputBorder="false" />
					</uni-forms-item>
					<!-- 上面选择检查计划回写上来的 -->
					<uni-forms-item label="隐患描述：" required name="hiddenDangerDescription">
						<uni-easyinput v-model="hiddenForm.hiddenDangerDescription" type="text" placeholder="请输入"
							:inputBorder="false" />

					</uni-forms-item>

					<uni-forms-item label="隐患责任单位：" required name="hiddenDangerDeptName">

						<custom-tree-select :listData="treeData" dataLabel="label" dataValue="id" :search="true"
							:mutiple="false" v-model="hiddenForm.hiddenDangerDeptName" />

						</custom-tree-select>

					</uni-forms-item>

					<uni-forms-item label="检查执行人：" required name="hiddenDangerExaminerName">
						<!-- <text> {{valiFormData.examineExecutorName}}</text> -->
						<uni-data-select :localdata="executorList" disabled
							v-model="hiddenForm.hiddenDangerExaminerName" />
					</uni-forms-item>
					<!-- 多选 -->
					<uni-forms-item label="隐患登记人：" required name="hazardRegistrantId">
						<custom-tree-select :listData="allUsers" dataLabel="nickName" dataValue="userId" :search="true"
							@selectChange="deptChange" :mutiple="true" v-model="hiddenForm.hazardRegistrantId" />

						</custom-tree-select>
					</uni-forms-item>


					<uni-forms-item label="抄送到部门：" required name="ccDepartmentId">
						<custom-tree-select :listData="treeData" dataLabel="label" dataValue="id" :search="true"
							:mutiple="false" v-model="hiddenForm.ccDepartmentId" />

						</custom-tree-select>
					</uni-forms-item>

					<uni-forms-item label="是否现场解决：" required name="isSiteSolution">
						<uni-data-checkbox v-model="hiddenForm.isSiteSolution"
							:localdata="solveOption"></uni-data-checkbox>
					</uni-forms-item>

				</uni-forms>
				<button @click="closeDrawer('showLeft')"><text class="word-btn-white">关闭</text></button>
			</view>
		</uni-drawer>
		<templtae v-if="manualVisible">
			<ManualSelect ref="manualChild" @manualCheck="manualCheckBack"></ManualSelect>
		</templtae>
	</view>
</template>

<script>
	import widowHeightMixins from "@/mixins/widowHeightMixins.js";
	import ManualSelect from "../otherViews/modal/manualSelect.vue"
	import {
		getNowTime
	} from "@/utils/nowTime.js"
	import ViewTable from "../otherViews/viewTable.vue"
	import {
		sendRegular,
		addRegular,
		submitRegular,
		deleteRegister,
		detailViewRegister
	} from "@/api/hiddenTrouble/periodShoot.js";
	import {
		listCheckPlan,
		getCheckPlan

	} from "@/api/hiddenTrouble/checkPlan.js"
	import {
		getInfo,
		listUser
	} from "@/api/system/user.js"
	import {
		deptTreeSelect
	} from "@/api/system/user";
	import {
		mapGetters
	} from "vuex"
	export default {
		mixins: [widowHeightMixins],
		components: {
			ManualSelect,
			ViewTable
		},
		onLoad(e) {
			// console.log(e, "e");
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('acceptDataFromOpenedPage', (data) => {
				this.queryForm.pageStatus = data.pageStatus
				// console.log("接受", data)
				this.detailObj = data.totalObj
				this.operateStatus = data.operateStatus
				this.checkId = data.checkId
				if (data.operateStatus == 1) {
					this.handleopen(data.totalObj.summaryTwo)
				}

			});
			// 动态设置标题
			uni.setNavigationBarTitle({
				title: `定期排查流程--填写`,
			});
		},
		data() {
			return {
				//隐患登记
				hiddenForm: {},
				hiddenData: [{
					text: '有隐患',
					value: true
				}, {
					text: '无隐患',
					value: false
				}],
				tableHead: [{
						key: 'inspectionStandard',
						title: '检查内容',
						width: '160'
					},
					{
						key: 'isHiddenDanger',
						title: '检查情况',
						width: '160'
					},
				],
				MockTableList: [{
						id: '00001',
						inspectionStandard: '测试1',
						isHiddenDanger: true
					},
					{
						id: '00002',
						inspectionStandard: '测试2',
						isHiddenDanger: false
					},
				],
				//详情
				detailObj: {},
				hiddenLevelOption: [{
						text: '一般隐患',
						value: 1
					},
					{
						text: '重大隐患',
						value: 2
					},

				],
				solveOption: [{
						text: '是',
						value: 1
					},
					{
						text: '否',
						value: 2
					},
				],
				//隐患登记表
				hiddentroubleInspectionRegisters: [],
				//当前选中
				current: 0,
				//标签
				items: ['检查记录表', '隐患登记表'],
				//选中ID
				checkId: null,
				//操作状态
				operateStatus: null,
				//上传参数对象
				queryForm: {},
				//手工选择弹窗
				manualVisible: false,
				//被检查单位的数据
				treeData: [],
				// 校验表单数据
				valiFormData: {},
				taskLevelOption: [],
				//所属检查计划的option
				checkPlanOption: [],
				//检查表内容
				tableData: [{
						id: "999",
						inspectionScopeName: "其他",
						inspectionCategoryName: "其他",
					},

				],
				localRes: {},
				// 每页数据量
				pageSize: 10,
				// 当前页
				pageCurrent: 1,
				// 数据总量
				total: 0,
				loading: false,
				//检查执行人
				executorList: [],
				// 动火人下拉框
				peopleOption: [{
						value: 0,
						text: "人员1"
					},
					{
						value: 1,
						text: "人员2"
					},
					{
						value: 2,
						text: "人员3"
					},
				],

				// 校验规则
				rules: {
					dept: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					name: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					age: {
						rules: [{
								required: true,
								errorMessage: "年龄不能为空",
							},
							{
								format: "number",
								errorMessage: "年龄只能输入数字",
							},
						],
					},
				},
			};
		},
		methods: {
			//登记按钮（打开抽屉）
			handleResigration(row) {
				// this.$refs['showLeft'].open()
				uni.navigateTo({
					url: `/pages/trouble/process/registration`,
					success: (res) => {
						res.eventChannel.emit('registrationAcct', {
							detail: this.detailObj.summaryTwo,
							checkId: this.checkId,
							tableId: row.id
						})
					}
				})
			},
			//关闭抽屉
			closeDrawer() {
				this.$refs['showLeft'].close()
			},
			//切换table表
			changeTable(e) {
				console.log("pppp", e.currentIndex)
				this.$nextTick(async () => {
					uni.showLoading({
						title: "加载中"
					})
					this.current = e.currentIndex
					if (e.currentIndex == 1) {
						let query = {
							regularId: this.checkId,
						};
						let res = await detailViewRegister(query);
						this.hiddentroubleInspectionRegisters = res.rows;

					}
					uni.hideLoading()
				})


			},
			//删除隐患登记表
			async handleDelete(row) {
				await deleteRegister(row.id);
				var index = this.hiddentroubleInspectionRegisters.indexOf(row);
				if (index !== -1) {
					this.hiddentroubleInspectionRegisters.splice(index, 1);
				}
				uni.showModal({
					title: "删除成功"
				})
			},

			/** 删除 */
			deleteTrouble(row) {
				// console.log("row===", row);
				var index = this.tableData.indexOf(row);
				if (index !== -1) {
					this.tableData.splice(index, 1);
				}
			},
			//处理详情接口数据回写上面
			handleopen(data) {
				this.valiFormData = data;
				this.tableData = data.hiddentroubleInspectionTables;
				this.valiFormData.approverIds = data.approverIds?.map((item) => {
					return {
						approverId: item,
					};
				});

				this.valiFormData.planUserName = data.examineExecutorName;
				this.valiFormData.pageStatus = this.queryForm.pageStatus
				let arr = data.examineParticipantIds.split(",");
				this.valiFormData.examineParticipantIds = arr?.map((item) => {
					return Number(item);
				});

				console.log("table内容", this.tableData)

			},
			/** 被检查部门部门下拉树结构 */
			async getDeptTree() {
				const response = await deptTreeSelect();
				this.treeData = response.data;
			},
			deptChange() {},
			// 手工选择按钮
			manualBtn() {
				this.manualVisible = true
				this.$nextTick(() => {
					this.$refs["manualChild"].changeShow()
				})
			},
			//获取用户的option
			async getUserOption() {
				let res = await listUser()
				console.log("获取用户", res)
			},
			//获取当前时间
			getTime() {
				let timer = getNowTime(0)
				this.valiFormData.taskNumber = `DQ${timer}`
			},
			//手工选择返回
			manualCheckBack(val) {
				// console.log("返回的", val)
				this.tableData = val
			},
			//获取所属检查计划数据
			async getCheckPlans() {
				this.localRes = uni.getStorageSync("userInfo")
				let query = {
					deptId: this.localRes.companyAccount,
					noPage: 1
				}
				let res = await listCheckPlan(query);
				this.checkPlanOption = res.rows

			},

			//计划的change事件
			handleChange(val) {
				if (val.length >= 1) {
					this.$set(this.valiFormData, 'taskLevel', val[0].planLevel)
				} else {
					this.$set(this.valiFormData, 'taskLevel', "")
				}

			},
			/** 获取当前登陆人信息 */
			async getUserInfo() {
				let res = await getInfo();
				// console.log("用户", res);
				this.executorList = [{
					value: res.user.userId,
					text: res.user.nickName,
				}, ];
				this.valiFormData.examineExecutorId = res.user.userId;
			},
			// 多选
			selectionChange(e) {
				console.log(e.detail.index)
				// this.selectedIndexs = e.detail.index
			},
			submit(ref) {
				this.$refs[ref]
					.validate()
					.then(async (res) => {


						if (this.operateStatus == 1) {
							let params = {

								regularId: this.checkId,
							}

							let res = await submitRegular(params);
							uni.showToast({
								title: `提交成功`,
							});
							uni.navigateTo({
								url: "/pages/trouble/index"
							})
						}

					})
					.catch((err) => {
						console.log("err", err);
					});
			},
		},
		mounted() {
			this.getCheckPlans()
			this.getUserInfo()
			this.getUserOption()
			this.getTime()
			this.getDeptTree()
		},
		computed: {
			...mapGetters(["allUsers"]),
		}
	};
</script>

<style lang="scss" scoped>
	.workApply-container {
		padding: 20rpx;
		background-color: #fff;
		overflow-y: auto;

		.table-container {

			// display: flex;
			// overflow-x: auto;
			// position: relative;
			// flex: 1;
			::v-deep {
				.uni-table {
					min-width: 520px !important;
				}
			}
		}

		.table-container .uni-table-body-wrapper {
			// position: relative;
		}

		.table-container .uni-table-body {
			// display: flex;
		}

		.fixed {
			width: 90px !important;
			position: sticky;
			right: 0;
			z-index: 2;
			background-color: #ffffff;
		}


		::v-deep {
			.uni-forms-item--border {
				border-top: 0 solid #000;
				border-bottom: 2rpx solid #e8eaec;
			}

			.uni-forms-item__label {
				width: 40% !important;
			}

			.uni-button {
				width: 60px;
				font-size: 12px;
			}

			.submit-btn {
				margin-top: 30rpx;
				background: #137ee9;
				border-radius: 10rpx;
			}
		}
	}
</style>